package org.iff.util;

import org.iff.util.JSONUtil;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class MultiThread {

    public static interface RunTask<T> {
        void run(T data, int index);
    }

    public static <T> void run(final List<T> taskData, final int threadNumber, final RunTask<T> task) throws Exception {
        AtomicInteger counter = new AtomicInteger(-1);
        ReentrantLock lock = new ReentrantLock();
        final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);// 参数为线程个数
        final int taskSize = taskData.size();
        for (int i = 0; i < threadNumber; i++) {
            new Thread(() -> {
                while (counter.get() < taskSize) {
                    int currentIndex = -1;
                    T data = null;
                    try {
                        lock.lock();
                        currentIndex = counter.incrementAndGet();
                        if (currentIndex >= taskSize) {
                            break;
                        }
                        data = taskData.get(currentIndex);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                    try {
                        task.run(data, currentIndex);
                    } catch (Exception e) {
                        System.out.println(currentIndex);
                        System.out.println(JSONUtil.toJsonString(data));
                        e.printStackTrace();
                    }
                }
                countDownLatch.countDown();// 线程计数器减一
            }).start();
        }

        // 线程启动后调用countDownLatch方法
        try {
            countDownLatch.await();// 需要捕获异常，当其中线程数为0时这里才会继续运行
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
